<template lang="pug">
.banner
  .banner-header
    .banner-header-title
      span 首页轮播图设置
      label 支持png、jpg格式图片。最多5张，建议尺寸1920*440
    .banner-header-handle
      el-button(name="primary" size="small" @click="save" v-if="$permission('AB-01001-004')") 应用到平台
  .banner-list
    .banner-item(v-for="item, index in fileList")
      .banner-item-body
        .banner-item-tag {{index + 1}}
        .banner-item-icons
          .handle-btn-icon(@click="moveUp(index)" v-if="$permission('AB-01001-001') && index != 0")
            .iconfont.icon-up
            label 上移
          .handle-btn-icon(@click="deleteFile(index)" v-if="$permission('AB-01001-002')")
            .iconfont.icon-delete
        .styles-item-change
          el-upload(
            action="#"
            :multiple="false"
            accept="image/png, image/jpeg, image/jpg, image/gif"
            ref="styleUpload"
            :show-file-list="false"
            :auto-upload="false"
            list-type="picture"
            :on-change="replaceBannerChange"
            )
            .styles-item-btn(slot="trigger" @click="changeBannerFile(item, index)" v-if="$permission('AB-01001-003')") 更换图片
        .banner-item-img(:style="item.fileUrl | filterUrl" v-if="item.fileUrl")
        .banner-item-img(v-if="!item.fileUrl")
          el-image(style="width: 100%; height: 100%", :src="item.url" fit="cover")
        .banner-item-bd
          .banner-item-material(v-if="item.type == 2")
            .material-img(:style="{ 'background-image': `url(${item.picImg})` }")
            .material-item-bd
              .material-item-title {{item.materialName}}
              .material-item-info {{item.companyName}}
          .banner-item-link(v-if="item.type == 1")
            .item-link-label 外部链接
            .item-link-bd {{item.url}}
          el-popover(
            popper-class="header-popover"
            placement="bottom-start"
            trigger="click"
            :visible-arrow="false"
          )
            .item-btn-downdrop
              .downdrop-item(@click="changeCate(item, 'fileList', 2)") 单个材料链接
              .downdrop-item(@click="changeLink(item, 'fileList', 1)") 外部链接
            .banner-item-btn(v-show="(item.url || item.picImg) && $permission('AB-01001-005')" slot="reference") 更换
          .banner-item-handles(v-if="item.type == 3 && $permission('AB-01001-005')")
            .banner-item-btn(@click="changeCate(item, 'fileList', 2)") 单个材料链接
            .banner-item-btn(@click="changeLink(item, 'fileList', 1)") 外部链接
    el-upload(
      action="#"
      :multiple="false"
      accept="image/png, image/jpeg, image/jpg, image/gif"
      ref="upload"
      :show-file-list="false"
      :auto-upload="false"
      :file-list="tempFileList"
      list-type="picture"
      :on-change="handleChange"
    )
      .banner-upload(slot="trigger" v-if="$permission('AB-01001-006')")
        .iconfont.icon-picture
        .banner-upload-info 添加图片
  outside-link-modal(:show="showLinkDialog", :item="currentItem" @close="linkHandleClose" @confirm="confirmLink")
  select-material-modal(:show="showMaterialModal" @close="closeMaterialModal" @confirm="confirmMaterialModal")
</template>

<script>
import { FileUpload, getBannerList, addBanner } from 'api'
import outsideLinkModal from '@/components/modal/outsideLinkModal'
import selectMaterialModal from '@/components/modal/selectMaterialModal'
let loading = ''
export default {
  name: 'banner',
  data () {
    return {
      fileList: [],
      tempFileList: [],
      currentItem: {},
      showLinkDialog: false,
      showMaterialModal: false,
      linkType: '',
      bannerKey: '',
      replaceBannerIndex: ''
    }
  },
  components: {
    outsideLinkModal,
    selectMaterialModal
  },
  computed: {},
  methods: {
    async handleChange (file, fileList) {
      try {
        if (this.fileList.length >= 5) {
          this.$message.error('banner图最多上传5张！')
          return
        }
        let temp = { ...file }
        temp.showDrop = false
        temp.type = 3
        temp.fileUrl = file.url
        delete temp.url
        this.fileList.push(temp)
        this.tempFileList = fileList
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async fileUpload (raw) {
      return new Promise(async (resolve, reject) => {
        try {
          let formData = new FormData()
          formData.append('Filedata', raw)
          formData.append("applicationId", 4)
          const { ResultSet } = await this.$axios.post(FileUpload, { formData: formData, isUpload: true }, { headers:{ "Content-Type": "multipart/form-data" } })
          resolve({ ...ResultSet.Result[0] })
        } catch (err) {
          console.log(err)
          reject(err)
        }
      })
    },
    moveUp (index) {
      this.fileList.splice(index - 1, 1, ...this.fileList.splice(index, 1 , this.fileList[index - 1]))
    },
    deleteFile (index) {
      this.$confirm('是否删除该张照片？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        this.fileList.splice(index, 1)
      })
    },
    changeCate (item, key, type) {
      this.showMaterialModal = true
      this.bannerKey = key
      this.linkType = type
      this.currentItem = { ...item }
    },
    changeLink (item, key, type) {
      this.showLinkDialog = true
      this.bannerKey = key
      this.linkType = type
      this.currentItem = { ...item }
    },
    linkHandleClose () {
      this.showLinkDialog = false
      this.bannerKey = ''
      this.currentItem = {}
    },
    changeBannerFile (item, index) {
      this.replaceBannerIndex = index
    },
    replaceBannerChange (file, fileList) {
      this.$set(this.fileList[this.replaceBannerIndex], 'fileUrl', file.url)
      this.tempFileList.push(file)
    },
    confirmLink (data) {
      let index = this[this.bannerKey].findIndex(item => item.id === data.id)
      this[this.bannerKey][index] = { ...data, type: this.linkType }
      this.showLinkDialog = false
      this.bannerKey = ''
      this.currentItem = {}
    },
    closeMaterialModal () {
      this.showMaterialModal = false
      this.bannerKey = ''
      this.currentItem = {}
    },
    confirmMaterialModal (data) {
      let index = this[this.bannerKey].findIndex(item => item.id === this.currentItem.id)
      this[this.bannerKey][index] = { ...this[this.bannerKey][index], ...data, type: this.linkType }
      this.showMaterialModal = false
      this.bannerKey = ''
      this.currentItem = {}
    },
    async getList () {
      try {
        const { ResultSet } = await this.$axios.post(getBannerList, { classification: 1 })
        ResultSet.Result.forEach(item => { item.showDrop = false })
        // this.banners = ResultSet.Result
        this.fileList = ResultSet.Result
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async save () {
      try {
        loading = this.$loading({
          lock: true,
          text: '保存中....',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        let imgs = []
        if (this.tempFileList.length) {
          imgs = await Promise.all(this.tempFileList.map(async (item) => {
            try {
              const file = await this.fileUpload(item.raw)
              return { fileId: file.fileId, tempUrl: item.url }
            } catch (err) {
              console.error('error: ' + JSON.stringify(err))
            }
          }))
        }
        this.fileList.forEach(item => {
          imgs.forEach(row => {
            if (item.fileUrl === row.tempUrl) item.fileId = row.fileId
          })
        })
        await this.$axios.post(addBanner, { showList: this.fileList, classification: 1 })
        this.$message.success('保存成功！')
        this.$refs.upload.clearFiles()
        setTimeout(() => {
          loading.close()
        }, 1000)
      } catch (err) {
        setTimeout(() => {
          loading.close()
        }, 1000)
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    init () {
      this.getList()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.init()
    })
  }
} 
</script>

<style lang="scss">
.banner-upload {
  .el-upload--picture-card {
    width: 100%;
    height: 100%;
    background: transparent;
    border: none !important;
  }
  .header-popover {
    &.el-popover {
      padding: 0 !important;
    }
  }
}
</style>

<style lang="scss" scoped>
.downdrop-enter-active,
.downdrop-leave-active {
  opacity: 0;
  transform: scale(1);
}
.downdrop-leave-active {
  transition: opacity .3s ease;
}
.downdrop-enter-active,.downdrop-leave-active {
  opacity: 0
}
.downdrop-enter-active .item-btn-downdrop,
.downdrop-leave-active .item-btn-downdrop {
  transform: scale(0);
  opacity: 0;
}
.banner {
  background: #fff;
  border-radius: 10px 10px 0 0;
  width: 100%;
  height: 100%;
  padding: 0 40px;
}
.banner-header {
  padding: 16px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #EDEDED;
}
.banner-header-title {
  span {
    display: inline-block;
    font-size: 16px;
    line-height: 24px;
    color: #3E4373;
    margin-right: 16px;
  }
  label {
    font-size: 12px;
    line-height: 20px;
    color: #8B8EAB;
  }
}
.banner-list {
  margin-top: 24px;
  display: flex;
  flex-wrap: wrap;
}
.banner-item {
  width: 33.33%;
  min-height: 218px;
  padding-right: 24px;
  padding-bottom: 24px;
  .banner-item-body {
    height: 100%;
    position: relative;
    border-radius: 6px;
    background: #F6F6F9;
    display: flex;
    flex-direction: column;
  }
  &:nth-child(3n) {
    margin-right: 0;
  }
  &:hover {
    .banner-item-icons {
      display: flex;
    }
    .styles-item-change {
      display: inline-block;
    }
  }
}
.banner-item-img {
  width: 100%;
  height: 114px;
  border-radius: 6px 6px 0 0;
  position: relative;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  .el-image {
    border-radius: 6px 6px 0 0;
  }
}
.banner-item-bd {
  flex: 1;
  padding: 16px;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
}
.banner-item-material {
  flex: 1;
  display: flex;
  align-items: center;
  .material-img {
    width: 58px;
    height: 42px;
    margin-right: 8px;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }
  .material-item-bd {
    max-width: 326px;
  }
  .material-item-title {
    font-size: 16px;
    line-height: 24px;
    color: #3E4373;
  }
  .material-item-info {
    font-size: 12px;
    line-height: 20px;
    color: #64698F;
    margin-top: 4px;
  }
  .material-item-info,
  .material-item-title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.banner-item-tag {
  width: 24px;
  height: 24px;
  line-height: 22px;
  text-align: center;
  font-size: 12px;
  color: #fff;
  background: #8676FF;
  border: 1px solid #FFFFFF;
  border-radius: 6px 0px;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}
.banner-item-icons {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 2;
  padding: 8px;
  align-items: center;
  display: none;
  .handle-btn-icon {
    margin: 0 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 4px 12px;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 6px;
    color: #fff;
    font-size: 14px;
    cursor: pointer;
    .iconfont {
      font-size: 24px;
    }
    label {
      cursor: pointer;
    }
  }
}
.banner-item-btn {
  padding: 2px 8px;
  font-size: 14px;
  line-height: 22px;
  background: #FFFFFF;
  color: #FF2E42;
  border-radius: 6px;
  cursor: pointer;
}
.banner-upload {
  width: 496px;
  height: 194px;
  border-radius: 6px;
  margin-bottom: 24px;
  background: #F6F6F9;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  cursor: pointer;
  .iconfont {
    font-size: 40px;
    color: #B2B4C7;
  }
  .banner-upload-info {
     font-size: 16px;
     color: #B2B4C7;
     margin-top: 12px;
   }
}
.item-link-label {
  font-size: 16px;
  line-height: 24px;
  color: #3E4373;
}
.banner-item-handles {
  display: flex;
  .banner-item-btn {
    margin-left: 16px;
  }
}
.item-link-bd {
  font-size: 12px;
  line-height: 20px;
  color: #FF2E42;
}
.item-btn-downdrop {
  position: absolute;
  z-index: 1;
  padding: 16px;
  background: #3B3E5C;
  border-radius: 6px;
  .downdrop-item {
    white-space: nowrap;
    color: #FFFFFF;
    font-size: 12px;
    line-height: 20px;
    margin-bottom: 16px;
    cursor: pointer;
    &:last-child {
      margin-bottom: 0;
    }
  }
  &:before {
    content: '';
    position: absolute;
    width: 20px;
    height: 20px;
    border-radius: 6px;
    background: #3B3E5C;
    top: 3px;
    transform: translateY(-50%) rotate(45deg);
  }
}
.styles-item-change {
  display: none;
  position: absolute;
  left: 8px;
  bottom: 88px;
  z-index: 1;
}
.styles-item-btn {
  width: 96px;
  height: 32px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 6px;
  color: #fff;
  font-size: 14px;
  line-height: 32px;
  text-align: center;
  cursor: pointer;
}
</style>
